import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { Device, RepairRequest, RepairPriority } from '../../models/device.model';
import { DeviceService } from '../../services/device.service';
import { RepairRequestService } from '../../services/repair-request.service';

@Component({
  selector: 'app-create-repair-request',
  templateUrl: './create-repair-request.component.html',
  styleUrls: ['./create-repair-request.component.scss']
})
export class CreateRepairRequestComponent implements OnInit {
  repairForm: FormGroup;
  devices: Device[] = [];
  loading = false;
  submitting = false;
  selectedDeviceId?: number;

  priorities = [
    { value: RepairPriority.Low, label: '低' },
    { value: RepairPriority.Medium, label: '中' },
    { value: RepairPriority.High, label: '高' },
    { value: RepairPriority.Critical, label: '紧急' }
  ];

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private deviceService: DeviceService,
    private repairRequestService: RepairRequestService
  ) {
    this.repairForm = this.fb.group({
      deviceId: ['', Validators.required],
      title: ['', [Validators.required, Validators.maxLength(200)]],
      description: ['', [Validators.required, Validators.maxLength(1000)]],
      priority: [RepairPriority.Medium, Validators.required],
      requestedBy: ['', [Validators.required, Validators.maxLength(100)]],
      estimatedCost: [null]
    });
  }

  ngOnInit(): void {
    this.loadDevices();
    
    // Check if deviceId is provided in query params
    this.route.queryParams.subscribe(params => {
      if (params['deviceId']) {
        this.selectedDeviceId = +params['deviceId'];
        this.repairForm.patchValue({ deviceId: this.selectedDeviceId });
      }
    });
  }

  loadDevices(): void {
    this.loading = true;
    this.deviceService.getAllDevices().subscribe({
      next: (devices) => {
        this.devices = devices;
        this.loading = false;
      },
      error: (error) => {
        console.error('Error loading devices:', error);
        this.loading = false;
      }
    });
  }

  onSubmit(): void {
    if (this.repairForm.valid) {
      this.submitting = true;
      const formValue = this.repairForm.value;
      
      const repairRequest: Partial<RepairRequest> = {
        deviceId: +formValue.deviceId,
        title: formValue.title,
        description: formValue.description,
        priority: formValue.priority,
        requestedBy: formValue.requestedBy,
        estimatedCost: formValue.estimatedCost || undefined
      };

      this.repairRequestService.createRepairRequest(repairRequest as RepairRequest).subscribe({
        next: (result) => {
          console.log('Repair request created:', result);
          this.router.navigate(['/repair-requests']);
        },
        error: (error) => {
          console.error('Error creating repair request:', error);
          this.submitting = false;
        }
      });
    } else {
      this.markFormGroupTouched();
    }
  }

  private markFormGroupTouched(): void {
    Object.keys(this.repairForm.controls).forEach(key => {
      const control = this.repairForm.get(key);
      control?.markAsTouched();
    });
  }

  isFieldInvalid(fieldName: string): boolean {
    const field = this.repairForm.get(fieldName);
    return !!(field && field.invalid && (field.dirty || field.touched));
  }

  getFieldError(fieldName: string): string {
    const field = this.repairForm.get(fieldName);
    if (field?.errors) {
      if (field.errors['required']) return `${fieldName} 是必填项`;
      if (field.errors['maxlength']) return `${fieldName} 长度超出限制`;
    }
    return '';
  }
} 